﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using BartonExtension;
using ResponseObject;
using Model;
using SqlServerWrapper;

namespace WebSrvs.NET.apis
{
    /// <summary>
    /// ZK_ActivityUploadHandler 的摘要描述
    /// </summary>
    public class ZK_ActivityUploadHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            ZKResponse response = new ZKResponse();
            try
            {
                int act_id = context.Request["act_id"].toInt32().Value;
                int store_id = context.Request["store_id"].toInt32().Value;
                string catalog_ids = context.Request["catalog_ids"].ToString();
                ActivityStatus status = (ActivityStatus)context.Request["act_status"].toInt32().Value;
                float sale_rate = context.Request["sale_rate"].toFloat().Value;
                string sale_title = context.Request["sale_title"].ToString();
                string sale_desc = context.Request["sale_desc"].ToString();
                float discount_rate = context.Request["discount_rate"].toFloat().Value;
                string time_from = context.Request["time_from"].ToString();
                string time_to = context.Request["time_to"].ToString();
                ActivityShowType on_show_type = (ActivityShowType)context.Request["on_show_type"].toInt32().Value;

                string images = "";
                if(context.Request.Files.Count > 0)
                    foreach (string key in context.Request.Files.AllKeys)
                    {
                        string filename = key + ".jpg";
                        images += !key.Equals(context.Request.Files.AllKeys.Last()) ? Path.GetFileNameWithoutExtension(filename) + "," : Path.GetFileNameWithoutExtension(filename);
                    }

                string connStr = SqlConnectionManager.GetConnStrFromConfig();
                int returnVal = -1;
                using (SqlConnection conn = SqlConnectionManager.CreateSqlConnection(connStr))
                {
                    conn.Open();
                    using (SqlCommand cmd = SqlCommandManager.Create(conn, CommandType.StoredProcedure))
                    {
                        cmd.CommandText = "proc_add_activity";
                        cmd.Parameters.Add("@activity_id", SqlDbType.Int).Value = act_id;
                        cmd.Parameters.Add("@store_id", SqlDbType.Int).Value = store_id;
                        cmd.Parameters.Add("@catalog_ids", SqlDbType.VarChar).Value = catalog_ids;
                        cmd.Parameters.Add("@sale_rate", SqlDbType.Float).Value = sale_rate;
                        cmd.Parameters.Add("@status", SqlDbType.Bit).Value = status;
                        cmd.Parameters.Add("@sale_desc", SqlDbType.VarChar).Value = sale_desc;
                        cmd.Parameters.Add("@sale_title", SqlDbType.VarChar).Value = sale_title;
                        cmd.Parameters.Add("@discount_rate", SqlDbType.Float).Value = discount_rate;
                        cmd.Parameters.Add("@time_from", SqlDbType.VarChar).Value = time_from;
                        cmd.Parameters.Add("@time_to", SqlDbType.VarChar).Value = time_to;
                        cmd.Parameters.Add("@images", SqlDbType.VarChar).Value = images;
                        cmd.Parameters.Add("@on_show_type", SqlDbType.Int).Value = on_show_type;
                        cmd.Parameters.Add("@return", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
                        cmd.ExecuteNonQuery();

                        returnVal = cmd.Parameters["@return"].Value.toInt32().Value;
                    }
                }
                if (returnVal != -1 && context.Request.Files.Count > 0)
                {
                    string path = context.Server.MapPath("~/data/images/activities/{0}/{1}/".FormatWith(store_id, returnVal));
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
                    foreach (string key in context.Request.Files.AllKeys)
                    {
                        HttpPostedFile file = context.Request.Files[key];
                        string filename = key + ".jpg";
                        file.SaveAs(path + filename);
                        ImageHelper.GenerateThumb(context.Server.MapPath("~/data/images/activities/{0}/{1}".FormatWith(store_id, returnVal)), filename, 320, 320);
                        images += !key.Equals(context.Request.Files.AllKeys.Last()) ? Path.GetFileNameWithoutExtension(filename) + "," : Path.GetFileNameWithoutExtension(filename);
                    }
                }
            }
            catch(Exception ex)
            {
                response.isProcessSuccess = false;
                response.errCode = ErrorCodes.CODE_ERR_INTERNAL_ERR;
                response.errMsg = ex.Message;
            }
            context.Response.Write(response.ToJson());
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}